package com.lwq.http.threads.utils;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.log4j.Logger;

import com.lwq.http.threads.users.UserThread;
import com.lwq.http.utils.model.HttpParamsMap;
import com.lwq.http.utils.model.HttpResult;

/**
* @author 作者 linweiqiang
* @version 创建时间：2017年10月24日 上午10:09:54
* 类说明
*/
public class TimeThread implements Runnable {
	private Logger logger = Logger.getLogger(TimeThread.class);
	private long startTime=0;
	private long sleepTime=0;
	private  ExecutorService es = null;
	private  String uri = null;
	private  Map<String,String> params = null;
	private  int uNumber = 1;
	private  int uThreads = 80;
	private  long uSleepT =  0;
	private  long sleepT =  0;
	private  long uTimeOut =  1000*60;
	private  long timeOut =  1000*60;
	private  int threads = 80;
	private  int number = 1;
	private  HttpParamsMap hpm = null;
	private HttpResult hr = null;
	private  CloseableHttpClient hc = null;
	public TimeThread(CloseableHttpClient hc ,String uri , Map<String,String> params ,HttpParamsMap hpm ,HttpResult hr,long startTime , long sleepTime,int uNumber, int uThreads,
		long uSleepT,long uTimeOut,int number ,int threads,long sleepT ,long timeOut 
			) {
		this.startTime=startTime;
		this.sleepTime = sleepTime;
		this.uri = uri;
		this.params = params;
		this.uNumber = uNumber;
		this.uThreads = uThreads;
		this.uSleepT =  uSleepT;
		this.sleepT =  sleepT;
		this.uTimeOut =  uTimeOut;
		this.timeOut =  timeOut;
		this.threads = threads;
		this.number = number;
		this.hpm = hpm;
		this.hr = hr;
		this.hc = hc;
	}
	
	public void run() {
		long nowTime = System.currentTimeMillis();
		long endTime = nowTime + startTime;
		es = Executors.newFixedThreadPool(threads);
		logger.info("time start");
		System.out.println("time start");
		while(System.currentTimeMillis()<endTime){
			try {
				for (int i = 0; i < number; i++) {
					es.submit(new UserThread(hc, uri, params,hpm, hr ,uNumber, uThreads, uTimeOut,sleepT,uSleepT));
				}
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		try {
			es.shutdown();
			if(!es.awaitTermination(timeOut, TimeUnit.MILLISECONDS)){
				es.shutdownNow();
			}
		} catch (Exception e) {
			es.shutdownNow();
		}
	}
}
